/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

requirejs(['jquery', 'util', 'fancyBox', 'datatables', 'ztree', 'ztree_loader'], function($, util, fancyBox, dataTables, ztree, treeLoader) {
    $(function() {
        // full height
        window.treeLoader = treeLoader;
        $('body').css('overflow', 'hidden');
        $('#categroys').css('height', $(window).height() - 60);
        $('#iframe_altercat').css('height', $(window).height());
        
        // 监听iframe onload事件，关闭loading动画层
        $('#iframe_altercat').on('load', function() {
            window.setTimeout(function() {
                $('#iframe_loading').fadeOut();
            }, 500);
        });
        
        // 目录树点击回调函数
        treeLoader.setting.callback.onClick = function(event, treeId, treeNode) {
            // 启动loading
            $('#iframe_loading').show();
            $('#iframe_altercat').attr('src', '?/WdminPage/alter_category/id=' + treeNode.dataId);
        };
        
        // 初始化目录树
        treeLoader.init('#_ztree', '?/vProduct/ajaxGetCategroys/r=' + (new Date()).getTime(), function() {
            $('.fix_bottom').show();
        });
        
        fnFancyBox('#add_category_btn', function() {
            $('#cat_name_f').focus();
            var snode = treeLoader.zTreeObj.getSelectedNodes(), pid = 0;
            if (snode) {
                pid = snode[0].dataId;
            }
            // [HttpPost]
            $('#add_cate_btn').click(function() {
                var catname = $('#cat_name_f').val();
                if (catname !== '') {
                    $.post('?/vProduct/ajaxAddCategroy', {
                        catname: catname,
                        pid: pid
                    }, function(r) {
                        if (parseInt(r) > 0) {
                            treeLoader.zTreeObj.addNodes(snode[0], {
                                name: catname,
                                dataId: parseInt(r)
                            });
                            $.fancybox.close();
                        }
                    });
                }
            });
        });
    });
});

function fnDelSelectCat() {
    var node = treeLoader.zTreeObj.getSelectedNodes();
    treeLoader.zTreeObj.removeNode(node[0]);
}

/**
 * 重新加载左侧分类树
 * @todo 重新加载之后刷新选中
 * @returns {undefined}
 */
function fnReloadTree() {
    treeLoader.zTreeObj.destroy();
    treeLoader.init('#_ztree', '?/vProduct/ajaxGetCategroys/r=' + (new Date()).getTime(), function() {
        $('.fix_bottom').show();
    });
}